package keni.html.android.framework.UI;

import java.util.Hashtable;
import java.util.Map;

import keni.html.android.framework.util.Constants;


import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

public class ObjectProvider extends ContentProvider {

	private static class DatabaseHelper extends SQLiteOpenHelper {

		private DatabaseHelper(Context context) {
			super(context, Constants.ObjectProviderMetaData.DATABASE_NAME,
					null, Constants.ObjectProviderMetaData.DATABASE_VERSION);

		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			
			 db.execSQL("CREATE TABLE " + Constants.Tables.TableNames.PRODUCT + " ("
	                    + Constants.Tables.ID + " INTEGER PRIMARY KEY,"
	                    + Constants.Tables.Proudct.MADEIN + " TEXT,"
	                    + Constants.Tables.Proudct.PRODUCTNAME + " TEXT"
	                    + ");");
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			
			
		}
	}

	private static final UriMatcher uriMatcher;
	static{
		uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(Constants.ObjectProviderMetaData.AUTHORITY, "*", Constants.ObjectProviderMetaData.INCOMING_OBJECT_COLLECTION_URI_INDICATOR);
		uriMatcher.addURI(Constants.ObjectProviderMetaData.AUTHORITY, "*/#", Constants.ObjectProviderMetaData.INCOMING_SINGLE_OBJECT_URI_INDICATOR);
	}
	private DatabaseHelper dbHelper;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db=dbHelper.getWritableDatabase();
		String tableName=uri.getPathSegments().get(0);
				
		int count;
		switch (uriMatcher.match(uri)) {
		case Constants.ObjectProviderMetaData.INCOMING_OBJECT_COLLECTION_URI_INDICATOR:
			count=db.delete(tableName, selection, selectionArgs);
			break;
		case Constants.ObjectProviderMetaData.INCOMING_SINGLE_OBJECT_URI_INDICATOR:
			String rowId=uri.getPathSegments().get(1);
			count=db.delete(tableName, BaseColumns._ID+ "=" + rowId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), 
                    selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
			
		}
		getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public String getType(Uri uri) {
		String tableName=uri.getPathSegments().get(0);
	    switch (uriMatcher.match(uri)) {
        case Constants.ObjectProviderMetaData.INCOMING_OBJECT_COLLECTION_URI_INDICATOR:
            return String.format(Constants.ObjectProviderMetaData.CONTENT_TYPE,tableName);

        case Constants.ObjectProviderMetaData.INCOMING_SINGLE_OBJECT_URI_INDICATOR:
            return String.format(Constants.ObjectProviderMetaData.CONTENT_ITEM_TYPE,tableName);

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		
		if(uriMatcher.match(uri)!=Constants.ObjectProviderMetaData.INCOMING_OBJECT_COLLECTION_URI_INDICATOR)
		{
			throw new IllegalArgumentException("Unknow URI "+uri);
		}
		String tableName=uri.getPathSegments().get(0);
		SQLiteDatabase db=dbHelper.getWritableDatabase();
		long rowId=db.insert(tableName, null, values);
		if(rowId>0)
		{
			Uri insertedObjectUri=ContentUris.withAppendedId(Uri.parse(Constants.ObjectProviderMetaData.CONTENT_URI+"/"+tableName), rowId);
			getContext().getContentResolver().notifyChange(insertedObjectUri, null);
			return insertedObjectUri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		dbHelper=new DatabaseHelper(getContext());
		return true;
	}

	private Map<String, String> createProjectionMap(String[] projection)
	{
		Map<String, String> projectionMap=new Hashtable<String, String>();
		for (String column : projection) {
			projectionMap.put(column, column);
		}
		
		return projectionMap;
	}
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder queryBuilder=new SQLiteQueryBuilder();
		String tableName=uri.getPathSegments().get(0);
		switch (uriMatcher.match(uri)) {
		case Constants.ObjectProviderMetaData.INCOMING_OBJECT_COLLECTION_URI_INDICATOR:
			queryBuilder.setTables(tableName);
		queryBuilder.setProjectionMap(createProjectionMap(projection));
			break;
		case Constants.ObjectProviderMetaData.INCOMING_SINGLE_OBJECT_URI_INDICATOR:
			queryBuilder.setTables(tableName);
			queryBuilder.setProjectionMap(createProjectionMap(projection));
			queryBuilder.appendWhere(BaseColumns._ID+ "=" 
        		    + uri.getPathSegments().get(1));
			break;

		default:
			  throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
	    SQLiteDatabase db = dbHelper.getReadableDatabase();
	   
        Cursor cursor = queryBuilder.query(db, projection, selection, 
        		   selectionArgs, null, null, sortOrder);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		
		SQLiteDatabase db=dbHelper.getWritableDatabase();
		String tableName=uri.getPathSegments().get(0);
		int count;
		switch (uriMatcher.match(uri)) {
		case Constants.ObjectProviderMetaData.INCOMING_OBJECT_COLLECTION_URI_INDICATOR:
			count=db.update(tableName, values,selection, selectionArgs);
			break;
		case Constants.ObjectProviderMetaData.INCOMING_SINGLE_OBJECT_URI_INDICATOR:
			String rowId=uri.getPathSegments().get(1);
			count=db.update(tableName,values ,BaseColumns._ID+ "=" + rowId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), 
                    selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
			
		}
		getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	
	
}
